package com.nehc.nettyserver.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * 缓存配置类
 * 使用Caffeine提供本地缓存
 * 
 * @author NEHC
 */
@Configuration
@EnableCaching
public class CacheConfig {

    /**
     * 配置缓存管理器
     */
    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        
        // 配置默认缓存策略
        cacheManager.setCaffeine(Caffeine.newBuilder()
                // 设置最后一次写入后经过固定时间过期
                .expireAfterWrite(60, TimeUnit.MINUTES)
                // 设置最后一次访问后经过固定时间过期
                .expireAfterAccess(30, TimeUnit.MINUTES)
                // 初始缓存空间大小
                .initialCapacity(100)
                // 最大缓存条数
                .maximumSize(1000));
        
        // 指定缓存名称列表
        cacheManager.setCacheNames(Arrays.asList(
                "messages", 
                "clientInfo", 
                "userMessages", 
                "messageStats", 
                "notifications"));
        
        return cacheManager;
    }
    
    /**
     * 配置消息缓存
     */
    @Bean
    public Caffeine<Object, Object> messagesCacheConfig() {
        return Caffeine.newBuilder()
                .expireAfterWrite(2, TimeUnit.HOURS)
                .initialCapacity(500)
                .maximumSize(10_000);
    }
    
    /**
     * 配置客户端信息缓存
     */
    @Bean
    public Caffeine<Object, Object> clientInfoCacheConfig() {
        return Caffeine.newBuilder()
                .expireAfterAccess(1, TimeUnit.HOURS)
                .initialCapacity(100)
                .maximumSize(1000);
    }
    
    /**
     * 配置用户消息缓存
     */
    @Bean
    public Caffeine<Object, Object> userMessagesCacheConfig() {
        return Caffeine.newBuilder()
                .expireAfterWrite(3, TimeUnit.HOURS)
                .initialCapacity(100)
                .maximumSize(500);
    }
    
    /**
     * 配置消息统计缓存
     */
    @Bean
    public Caffeine<Object, Object> messageStatsCacheConfig() {
        return Caffeine.newBuilder()
                .expireAfterWrite(5, TimeUnit.MINUTES)
                .initialCapacity(20)
                .maximumSize(100);
    }
    
    /**
     * 配置通知缓存
     */
    @Bean
    public Caffeine<Object, Object> notificationsCacheConfig() {
        return Caffeine.newBuilder()
                .expireAfterWrite(12, TimeUnit.HOURS)
                .initialCapacity(100)
                .maximumSize(1000);
    }
} 